<template>
	<div class="echart"></div>
</template>
  
<script>
import * as echarts from 'echarts';
export default {
	name: 'Echart',
	components: {},
	props: {
		dataSource: {
			default: null,
		},
	},
	data() {
		return {
			title: '',
			xAxisData: [],
			yAxisData: [],
			myChart: null,
			timer: null,
		};
	},
	watch: {
		dataSource: {
			// 监听 props.dataSource 的变化
			handler(newVal, _) {
				this.handleDataSource(newVal);
			},
			deep: true,
			immediate: true,
		},
	},
	created() {},
	mounted() {
		window.addEventListener('resize', this.resizeChart);
	},
	beforeUnmount() {
		window.removeEventListener('resize', this.resizeChart);
	},
	methods: {
		handleDataSource(obj) {
			if (!obj) return;
			// console.log("当前组件接收数据源为：", obj);

			this.title = obj.title || '';
			this.xAxisData = obj.xAxisData || [];
			this.yAxisData = obj.yAxisData || [];

			this.$nextTick(() => {
				// console.log("当前组件 id 为：", this.$el.id);
				this.initChart();
				this.resizeChart();
			});
		},

		// 获取 series 数据
		getSeries(yAxisData) {
			return yAxisData.map((item) => ({
				name: item.name || '',
				type: 'line',
				smooth: item.smooth || false,
				data: item.data || [],
				lineStyle: {
					width: 1,
				},
			}));
		},
		
		// 获取 echart 配置项
		getOption() {
			return {
				title: {
					text: this.title,
				},
				tooltip: {
					trigger: 'axis',
				},
				legend: {
					data: this.yAxisData.map((item) => item.name),
				},
				grid: {
					left: '2%',
					right: '2%',
					bottom: '2%',
					containLabel: true,
				},
				toolbox: {
					feature: {
						saveAsImage: {},
					},
				},
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: this.xAxisData,
				},
				yAxis: {
					type: 'value',
				},
				series: this.getSeries(this.yAxisData),
			};
		},
		
		// 初始化 echart 图表
		initChart() {
			var chartDom = document.getElementById(this.$el.id);
			if (!chartDom) return;

			echarts.dispose(chartDom);
			var myChart = echarts.init(chartDom);
			var option = this.getOption();
			option && myChart.setOption(option);
			this.myChart = myChart;
		},
		
		// 重置 echart 尺寸
		resizeChart() {
			setTimeout(() => {
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					if (this.myChart) {
						this.myChart.resize();
					}
				}, 200);
			});
		},
	},
};
</script>
  
<style scoped lang="scss">
.echart {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	background-color: #fff;
}
</style>